<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="108px">
      <el-form-item label="姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          size="small"
        />
      </el-form-item>
      <!-- <el-form-item label="姓名" prop="stuId">
        <el-select v-model="queryParams.stuId" clearable filterable placeholder="请选择姓名">
          <el-option
            v-for="item in namelist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="small">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级">
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.label"
            :value="parseInt(item.id)"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="药品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入药品名称"
            size="small"
          />
        </el-form-item>
        <el-form-item label="用药方法" prop="usageDosage">
          <el-input
            v-model="queryParams.usageDosage"
            placeholder="如：取10ml糖浆，倒入饮水杯中，加入50ml的温开水冲服即可。"
            type="input"
            size="small"
          />
        </el-form-item>
        <el-form-item label="用药用量" prop="usageMeasure">
          <el-input
            v-model="queryParams.usageMeasure"
            placeholder="请输入用药用量"
            type="input"
            size="small"
          />
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="queryParams.applyStatus" placeholder="请选择设备状态">
              <el-option
                v-for="dict in dict.type.medicant_apply"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                size="small">
              </el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="姓名" align="center" prop="studentName"/>
      <el-table-column label="班级" align="center" prop="className"/>
      <el-table-column label="药品名称" align="center" prop="name"/>
      <el-table-column label="喂药频次" align="center" prop="frequency"/>
      <el-table-column label="开始时间" align="center" prop="startDate"/>
      <el-table-column label="结束时间" align="center" prop="endDate"/>
      <el-table-column label="用药方法" align="center" prop="usageDosage"/>
      <el-table-column label="用药用量" align="center" prop="usageMeasure"/>
      <el-table-column label="申请状态" align="center" prop="applyStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.medicant_apply" :value="scope.row.applyStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="药品图片" align="center" prop="img">
        <template slot-scope="scope">
          <el-image
            style="width: 120px;height: 60px;"
            :src="scope.row.img"
            lazy
            :preview-src-list="[scope.row.img]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >管理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级" prop="classId">
          <el-select :disabled='isDisabled' v-model="form.classId" clearable filterable placeholder="请选择班级" @change="getStuchange">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.label"
              :value="parseInt(item.id)"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="stuId">
          <el-select :disabled='isDisabled' v-model="form.stuId" clearable filterable placeholder="请选择姓名">
            <el-option
              v-for="item in namelist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="药品名称" prop="name">
          <el-input
            :disabled='isDisabled'
            v-model="form.name"
            placeholder="请输入药品名称"
            size="small"
          />
        </el-form-item>
        <el-form-item label="使用方法" prop="usageDosage">
          <el-input
            v-model="form.usageDosage"
            :disabled='isDisabled'
            placeholder="如：取10ml糖浆，倒入饮水杯中，加入50ml的温开水冲服即可。"
            type="input"
            size="small"
          />
        </el-form-item>
        <el-form-item label="单次用量" prop="usageMeasure">
          <el-input
            v-model="form.usageMeasure"
            :disabled='isDisabled'
            placeholder="请输入单次用量"
            type="input"
            size="small"
          />
        </el-form-item>
<!--        <el-form-item label="用药原因" prop="reason">-->
<!--          <el-input-->
<!--            v-model="form.reason"-->
<!--            placeholder="请输入用药原因"-->
<!--            type="textarea"-->
<!--            size="small"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-row v-for="(item,index) in form.medicantArray" :key="index"> 
          <el-form-item label="喂药时间" :prop="'medicantArray.'+index" :rules="rules.medicantArray">
            <el-time-picker
              :disabled='isDisabled'
              v-model="form.medicantArray[index]"
              value-format="HH:mm"
              :picker-options="{
      selectableRange: '8:30:00 - 17:30:00'
    }"
              placeholder="喂药时间">
            </el-time-picker>
            <i v-if="index!==0&&isDisabled==false" class="el-icon-circle-close" style="margin-left: 20px;cursor: pointer;" @click="handleDelTime(index)"></i>
          </el-form-item>
        </el-row>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable size="small"
                          v-model="form.startDate"
                          :disabled='isDisabled'
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker clearable size="small"
                          v-model="form.endDate"
                          :disabled='isDisabled'
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="药品图片" prop="img">
          <el-image
            v-if="isDisabled"
            :src="form.img"
            lazy
            :preview-src-list="[form.img]">
          </el-image>
          <imageUpload v-else v-model="form.img" :limit="1"/>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="form.applyStatus" placeholder="请选择设备状态">
              <el-option
                v-for="dict in dict.type.medicant_apply"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                size="small">
              </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled='isDisabled' @click="handleAddTime">新增喂药时间</el-button>

<!--        <el-button @click="addFeed">新增用药</el-button>-->
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>


import {addYdevicerecord, delYdevicerecord, listYdevice, selectName, updateYdevicerecord} from '@/api/base/device'
import {selectClazz} from "@/api/base/clazz";
import {addmedicantApply, delmedicantApply, medicantApply, updatemedicantApply} from "@/api/base/ill";

export default {
  name: "feedapply",
  dicts:['medicant_apply'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolCode:this.$store.getters.schoolCode,
        studentName: '',
        classId: null,
        name: '',
        usageDosage: '',
        usageMeasure: '',
        applyStatus: null
      },
      classList: [],
      total: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {},
      namelist:[],
      // 表单校验
      rules: {
        stuId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        usageDosage: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        usageMeasure: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        medicantArray:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        img:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      },
      isDisabled:false,//修改的时候禁用

    };
  },
  created() {
    //用户名
    this.getNamelist()
    //班级
    this.getQueryClazzList();

    this.getList()
  },
  methods: {
    getStuchange(){
      this.getNamelist();
      this.$set(this.form,'stuId',null)
    },
    /**新增喂药时间**/
    handleAddTime(){
      this.form.medicantArray.push('')
    },
    handleDelTime(index){
      this.form.medicantArray.splice(index,1)
    },
    /** 查询班级列表 */
    async getQueryClazzList() {
      try{
        this.loading = true;
        const {rows}=await selectClazz();
        this.classList=rows.map(item=>{
          return {
            id:item.id,
            label:item.title,
          }
        })
        this.loading = false;
      }catch (e) {
        console.log(e)
      }
    },
    /**查询用户列表*/
    async getNamelist(){

      try {
         const obj ={
                 schoolCode:this.$store.getters.schoolCode,
                 classId:this.form.classId
          }
        this.loading = true;
        const data=await selectName(obj)
            this.namelist=data.rows.map(item=>{
            return{
              label:item.name,
              value:item.id,
            }
          })
      } catch (e){
        console.log(e)
      }
    },
    async getList() {
      try {
        this.loading = true;
        const data=await medicantApply(this.queryParams);
        this.studentList = data.rows;
        this.total = data.total;
        this.loading = false;
      } catch (e) {
        console.log(e)
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatemedicantApply(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addmedicantApply(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delmedicantApply(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const id = row.id || this.ids
      this.form = Object.assign({}, this.form, row)
      this.open = true;
      this.title = "修改喂药管理";
      this.isDisabled = true
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isDisabled = false
      this.form.medicantArray.push('')
      this.title = "添加喂药管理";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        deviceName: null,
        userId: null,
        userName: null,
        classId: null,
        roomName: null,
        deviceType: null,
        schoolCode: null,
        status: null,
        medicantArray:[],
      };
      this.resetForm("form");
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog .el-form-item__content {
  width: 67%;
}
::v-deep .el-select{
  width: 100%;
}
</style>
